package com.csc.usermanagement.admin;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;

/**
 * Servlet implementation class UpdateDeleteServlet
 */
@WebServlet("/UpdateDelete")
public class UpdateDeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateDeleteServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String actionType = req.getParameter("btnSubmit");
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		String type = req.getParameter("type");
		String registeredDate = req.getParameter("registeredDate");

		Connection conn = null;
		PreparedStatement stmt = null;
		String deleteSQL = "delete from user where UserName = ?";
		String updateSQL = "update user set "
				+ "Password = ?, Type = ?, RegisteredDate = ?"
				+ "where UserName = ?";
		try {
			conn = UserManagementDbConnector.getConnection();
			if (actionType.equals("Delete")) {
				if (!userName.equals(req.getSession().getAttribute("username")
						.toString())) {
					stmt = conn.prepareStatement(deleteSQL);
					stmt.setString(1, userName);
					stmt.executeUpdate();
					req.setAttribute("msg", "Successfully delete one row from user.");
					req.setAttribute("msgType", "Success");
					req.getRequestDispatcher("/ListAllUsers").forward(req, resp);
					
				} else {
					
					req.setAttribute("msgType", "Failed");
					req.setAttribute("msg","Can not delete current user");
					req.getRequestDispatcher("/ListAllUsers").forward(req,
							resp);
				}
				
			} else if (actionType.equals("Update")) {
				if ( (!type.equals("user")) && (!type.equals("admin")) ){
					req.setAttribute("msgType", "Failed");
					req.setAttribute("msg", "User's type must be either 'admin' or 'user'");
					req.getRequestDispatcher("/ListAllUsers").forward(req, resp);
				} else {
					stmt = conn.prepareStatement(updateSQL);
					stmt.setString(1, password);
					stmt.setString(2, type);
					stmt.setString(3, registeredDate);
					stmt.setString(4, userName);
					stmt.executeUpdate();
					req.setAttribute("msgType", "Success");
					req.setAttribute("msg", "Successfully updated one row from user.");
					req.getRequestDispatcher("/ListAllUsers").forward(req, resp);
				}
				
			}
			stmt.close();
			conn.close();
		} catch (SQLException se) {
			se.printStackTrace();
		}
	}

}
